# testes-kmeans.R

# kmeans()
# http://stat.ethz.ch/R-manual/R-patched/library/stats/html/kmeans.html

# tutorial
# http://www.statmethods.net/advstats/cluster.html


# > d <- matrix( c( c(1,2,3,4,5,6), c(50, 10, 40,40, 30, 60)  ), ncol=2)
# > plot(d)
# > plotClusters(d, 3)

library(cluster)

erronclusters <- function(Data, nclusters)
{
	# kmeans() e pam() sao identicos

	# kmeans
	#cl <- kmeans(Data, n)
	#clusters <- cl$cluster
	#centers <- cl$centers
	# nao sei como usar o silhouette com o kmeans()

	# pam
	cl <- pam(Data, nclusters)
	clusters <- cl$clustering
	centers <- cl$medoids
	erro <- mean(silhouette(cl)[,3])
	erro
}

nroclusters <- function(Data)
{
	erro_menor <- Inf
	lim <- min(length(Data)-2, 8)
	for(n in 2:lim) {
		erro <- erronclusters(Data, n)
		if(erro < erro_menor) {
			erro_menor <- erro
			nclusters <- n
		}
	}
	nclusters
}

ptscluster <- function(Data, nclusters)
{
	pts <- NULL
	cl <- pam(Data, nclusters)
	clusters <- cl$clustering
	for(n in 1:nclusters)
		pts <- c(pts, list(Data[clusters == n]))
	pts
}

plotClusters <- function(Data, nclusters)
{
	cl <- pam(Data, nclusters)
	plot(Data, col = cl$clustering, main = paste('nclusters:', nclusters))  # pontos
}

plotClustersKmeans <- function(Data, nclusters)
{
	cl <- kmeans(Data, nclusters)
	plot(Data, col = cl$clusters, main = paste('nclusters:', nclusters))  # pontos
}

# começar por dividir em frequências

freqs <- function(Data, nclasses)
{
	h <- hist(Data, nclass=nclasses, plot=FALSE)
	x <- h$breaks[-1]
	y <- h$counts
	matrix(c(x,y), ncol=2)
}

#source('dados.R')

#f <- freqs(Danos(5), 8)
#nclusters <- nroclusters(f)
#print(ptscluster(f, nclusters))

